import 'package:flutter/material.dart';
import 'package:flutter_common_fragement/common/base/view/base_view.dart';
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';

import '../../utils/index.dart';
import '../base_controller/loading_controller.dart';
import '../common/index.dart';
import '../state/page_state.dart';
import '../view_model/base_view_model.dart';

abstract class BasePage<VM extends BaseViewModel> extends BaseView
    with RouteAware, _RouterHandler {
  /// 个人觉得这个实例抛出去有点奇怪  所以做为私有变量～～～
  final VM _viewModel;

  /// 路由名字
  final String? pageName;

  BasePage(this._viewModel, {this.pageName});

  /// page数据的集合
  static final List<BasePage> _pageList = [];

  List<Type> get pageList => _pageList.map((e) => e.runtimeType).toList();

  /// loading控制器（暂未用到，暂时混入了toastMixin）
  final LoadingController loadingController = LoadingController();

  /// 初始化widget 在navigator进行操作入栈的时候 必须初始化此基类
  Widget get initWidget => _createWidget();

  /// 修改路由初始化的过程生成的基础 base page
  Widget _createWidget() {
    return _PageWidget<VM>(
      basePage: this,
      viewModel: _viewModel,
    );
  }

  //重写底层视图
  //Widget child:build之后的试图
  Widget buildBuilder(BuildContext context, Widget child) {
    return child;
  }

  /// 保证页面活跃 这个在页面初始化的时候调用方法 然后在state注册的时候进行操作
  void setKeepAlive() => isAutoKeepAlive = true;

  @override
  void initState() {
    super.initState();

    /// 添加当前页面的路由
    _pageList.add(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    /// 路由订阅
    routeObserver.subscribe(
        this, ModalRoute.of(state.context) as PageRoute<dynamic>);
  }

  @override
  void dispose() {
    super.dispose();
    if (_pageList.contains(this)) {
      /// 删除当前页面的路由
      _pageList.remove(this);
    }

    /// 取消路由订阅
    routeObserver.unsubscribe(this);
  }

  /// 路由观察者的操作
  @override
  void didPush() {
    super.didPush();
    handleDidPush();
  }

  @override
  void didPop() {
    super.didPop();
    handleDidPop();
  }

  @override
  void didPopNext() {
    super.didPopNext();
    handleDidPopNext();
  }

  @override
  void didPushNext() {
    super.didPushNext();
    handleDidPushNext();
  }
}

class _PageWidget<VM extends BaseViewModel> extends StatefulWidget {
  final BasePage basePage;
  final VM viewModel;

  const _PageWidget(
      {super.key, required this.basePage, required this.viewModel});

  @override
  PageWidgetState<VM> createState() => PageWidgetState<VM>();
}

class PageWidgetState<VM extends BaseViewModel>
    extends PageState<_PageWidget<VM>> {
  late BasePage _basePage;

  @override
  void initState() {
    super.initState();
    _basePage = widget.basePage;
    _basePage.registerState(this);
    _basePage.initState();
    widget.viewModel.registerState(this);
    widget.viewModel.viewModelInit();
    widget.viewModel.initData();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      /// 给viewModel实例放置context
      widget.viewModel.setContext(context);

      /// 保证initEvent的context初始化成功
      widget.viewModel.viewModelInitForContext(context);

      ///
      _basePage.initStateForContext(context);
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _basePage.didChangeDependencies();
  }

  // /// 个人觉得这个生命周期不用组装跟修改（除非你要修改setState的刷新算法）
  // @override
  // void didUpdateWidget(covariant _PageWidget oldWidget) {
  //   super.didUpdateWidget(oldWidget);
  // }
  @override
  void didUpdateWidget(covariant _PageWidget<VM> oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
  }

  @override
  void reassemble() {
    // TODO: implement reassemble
    super.reassemble();
    _basePage.reassemble();
    widget.viewModel.reassemble();
  }

  @override
  void dispose() {
    super.dispose();

    /// 取消当前所有的toast
    widget.viewModel.clearAllToast();
    widget.viewModel.viewModelDispose();
    _basePage.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ChangeNotifierProvider<VM>(
      create: (BuildContext context) => widget.viewModel,
      child: _ReBuildWidget(
        builder: (context, _) => _basePage.build(context),
      ),
    );
  }
}

class _ReBuildWidget extends SingleChildStatelessWidget {
  const _ReBuildWidget({
    super.key,
    required this.builder,
    super.child,
  });

  final Widget Function(
    BuildContext context,
    Widget? child,
  ) builder;

  @override
  Widget buildWithChild(BuildContext context, Widget? child) {
    return builder(
      context,
      child,
    );
  }
}

class BasePageRoute extends MaterialPageRoute {
  final String? routerName;

  BasePageRoute({
    required BasePageRouteBuilder build,
    RouteSettings? settings,
    super.maintainState,
    super.fullscreenDialog,
    this.routerName,
  }) : super(
            builder: (context) {
              /// 使用自定义的BasePageRouteBuilder 不然无法使用BasePage
              return build(context).initWidget;
            },
            settings: settings ?? RouteSettings(name: routerName));
}

/// 自定义的RouteBuilder 通过实例化BasePage来拿到initWidget
typedef BasePageRouteBuilder = BasePage Function(BuildContext context);

/// 路由处理
mixin _RouterHandler implements HandleRouteNavigate {
  @override
  void handleDidPop() {
    Log.d("已经pop的页面::::$runtimeType");
  }

  @override
  void handleDidPush() {
    Log.d("push后，显示的页面::::$runtimeType");
  }

  @override
  void handleDidPopNext() {
    Log.d("pop后，将要显示的页面::::$runtimeType");
  }

  @override
  void handleDidPushNext() {
    Log.d("push后，被遮挡的页面::::$runtimeType");
  }
}

/// 路由处理的接口
abstract class HandleRouteNavigate {
  void handleDidPush();

  void handleDidPop();

  void handleDidPopNext();

  void handleDidPushNext();
}
